<template>
  <div class="content">
    <Form ref="formValidate" :model="dishForm" :label-width="80">
      <div class="formBox" style="margin-bottom: 20px">
        <div class="formBox-item">
          <FormItem label="菜肴编号" prop="dishCode">
            <Input v-model="dishForm.dishCode" maxlength="20" clearable placeholder="请输入菜肴编号" style="width: 200px">
            </Input>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="菜肴名称" prop="dishName">
            <Input v-model="dishForm.dishName" maxlength="20" clearable placeholder="请输入菜肴名称" style="width: 200px">
            </Input>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="菜肴类别" prop="dishCategory">
            <Select v-model="dishForm.dishCategory" style="width: 200px" placeholder="请选择菜肴类别" clearable>
              <Option :value="item.dishCategory" v-for="(item, index) in materialTypeList" :key="index">{{
                item.dishCategory }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="是否常用" prop="dishStatus">
            <Select v-model="dishForm.dishStatus" style="width: 200px" placeholder="请选择常用状态" clearable>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">

          <FormItem label="是否为新增菜肴" prop="isSystemDish" :label-width="130">
            <Select v-model="dishForm.isSystemDish" style="width: 200px" placeholder="请选择新增菜肴" clearable>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>
          </FormItem>
        </div>
        <div class="formBox-item">
          <FormItem label="是否为个性化菜肴" prop="isPersonalized" :label-width="130">
            <Select v-model="dishForm.isPersonalized" style="width: 200px" placeholder="全部" clearable>
              <Option value="">全部</Option>
              <Option value="0">否</Option>
              <Option value="1">是</Option>
            </Select>
          </FormItem>
        </div>
        <cusButton class="mr_20" type="primary" @onClick="
          pages.page = 1;
        onInit();
        ">查询</cusButton>
        <cusButton class="mr_20" type="primary" @onClick="reset()">重置</cusButton>
      </div>
    </Form>
    <div class="content-bottom">
      <div class="btnBox">
        <div>
          <cusButton class="mr_20" type="primary" @onClick="syncOrganLocalDish" :disabled="disabledCount">同步</cusButton>
          <span style="font-size: 16px;line-height: 35px">{{
            `倒计时${countDown}后可再次同步`
          }}</span>
        </div>
        <div>

          <cusButton class="mr_20" type="primary" @onClick="onAdd()" ghost>添加</cusButton>
          <cusButton type="primary" @onClick="onImport()" >导入菜肴</cusButton>
        </div>
      </div>
      <div class="tableBox">
        <cusTable border :loading="loading" :columns="columns" :data="data" :bottomClass="['cus-page']">
          <template slot-scope="{ row }" slot="dishUrl">
            <div style="display: flex; justify-content: center">
              <div class="table-cell-img">
                <img :src="row.dishUrl" alt="" class="" border="0" onload="autosize(this,50,50);"
                  @click="$cu.previewImage(row.dishUrl)" />
              </div>
            </div>
          </template>
          <template slot-scope="{ row }" slot="isSystemDish">
            <div>{{ row.isSystemDish == 0 ? "否" : "是" }}</div>
          </template>
          <template slot-scope="{ row }" slot="dishStatus">
            <div>
              {{ row.dishStatus === true ? "是" : "否" }}
              <i-switch :true-value="true" :false-value="false" v-model="row.dishStatus"
                @on-change="ifSwitchChange(row, 0)">
                <!-- <span slot="open">是</span>
               <span slot="close">否</span> -->
              </i-switch>
            </div>
          </template>
          <template slot-scope="{ row }" slot="usableStatus">
            <div>
              {{ row.usableStatus == 1 ? "是" : "否" }}
              <i-switch :true-value="true" :false-value="false" :value="row.usableStatus"
                @on-change="ifSwitchChange(row, 1)">
                <!-- <span slot="open">是</span>
               <span slot="close">否</span> -->
              </i-switch>
            </div>
          </template>
          <template slot-scope="{ row }" slot="operation">
            <div class="flex">
              <cus-button type="text" size="small" :style="{ color: 'green', padding: '0 8px' }"
                @onClick="onDetail(row)">
                营养标签
              </cus-button>
              <cus-button type="text" size="small" :style="{ color: '#1E6FFF', padding: '0 8px' }"
                @onClick="onEdit(row)">

                {{ row.isPersonalized ? '编辑' : '详情' }}
              </cus-button>
            </div>
          </template>
        </cusTable>
        <div style="width: 100%; display: flex; justify-content: flex-end">
          <cus-page :data="pages" class="mt_20" @pageChange="dishSearchListApi"></cus-page>
        </div>
      </div>
    </div>
    <!-- 导入 -->
    <cus-uploadModal ref="cusUploadNutritionTagModal" :temp-src="exportNutritionTagTemp" :uploadFnc="uploadNutritionTag"
      titleName="导入菜肴"
      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
      @onBeforeUpload="onBeforeUpload" @onError="onError" @onOk="exprotInit"></cus-uploadModal>
    <!-- 添加、编辑菜肴 -->
    <addDishesModal ref="addDishesModal"></addDishesModal>
    <!-- 营养标签 -->
    <dishesTags ref="dishesTags"></dishesTags>
    <!-- 是否常用提示 -->
    <cus-modal ref="dishStatusModal" width="500" title="提示：">
      <div>{{ dishStatusErrorList }}</div>
      <div slot="footer">
        <slot name="footer">
          <div class="modal-footer"></div>
        </slot>
      </div>
      <Spin size="large" fix v-if="loading"></Spin>
    </cus-modal>
  </div>
</template>

<script>
import {
  getDishListType,
  dishSearchList,
  downloadDishInportExcelTemplate,
  examineInportDishExcel,
  inportLocalDishExcel,
  localDishDelete,
  postApiBasicUdateDishStatus,
  postApiUpdateDishUsableStatus
} from "@/api/business/dishesModule";
import { syncOrganLocalDish } from "@/api/business/business";
import addDishesModal from "./components/addDishesModal";
import dishesTags from "./components/dishesTags";

export default {
  components: { addDishesModal, dishesTags },
  data() {
    return {
      ruleValidate: {},
      dishForm: {
        dishName: "", // 菜肴名称
        dishCategory: "", // 菜肴分类
        dishStatus: "", // 常用状态
        dishCode: "", // 菜肴编码
        isSystemDish: "",
        isPersonalized: '',
      },
      file: null,
      dishStatusErrorList: [], // 是否常用Switch不可操作错误提示信息
      materialTypeList: [], // 菜肴分类列表
      exportNutritionTagTemp: downloadDishInportExcelTemplate, // 下载模板地址
      uploadNutritionTag: examineInportDishExcel, //
      inportLocalDishExcel: inportLocalDishExcel,
      loading: false,
      data: [],
      columns: [
        {
          title: "序号",
          width: 70,
          type: "index",
          align: "center"
        },
        {
          title: "菜肴编码",
          key: "dishCode",
          align: "center"
        },
        {
          title: "菜肴名称",
          key: "dishName",
          align: "center"
        },
        {
          title: "菜肴类别",
          key: "dishType",
          align: "center"
        },
        {
          title: "图片",
          slot: "dishUrl",
          align: "center"
        },
        {

          title: "是否有价格",
          slot: "dishStatus",
          align: "center"
        },
        {
          title: "是否可用",
          slot: "usableStatus",
          align: "center"
        },
        {
          title: "个性化菜肴",
          slot: "isPersonalized",
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "span",
                `${params.row.isPersonalized == 0 ? '否' : '是'}`
              ),
            ]);
          },
        },
        {
          title: "是否为新增食材",
          slot: "isSystemDish",
          align: "center"
        },
        {
          title: "操作",
          width: 180,
          fixed: "right",
          slot: "operation",
          align: "center"
        }
      ],
      pages: {
        page: 1,
        pageSize: 10,
        pageTotal: 0
      },
      countDown: "5分00秒",
      disabledCount: false,
      timer: null
    };
  },
  mounted() {
    this.getDishListTypeApi();
    this.dishSearchListApi();
    window.addEventListener("resize", this.resizeHandle, true);
  },
  methods: {
    syncOrganLocalDish() {
      this.disabledCount = true;
      this.syncInf();
      syncOrganLocalDish().then(res => {
        if (res.retCode == 2000) {
          this.$Message.success('同步成功')
        }
      });
    },
    //同步数据
    syncInf() {
      this.countDown = "5分00秒";
      let min = 5;
      let second1 = 0;
      let second2 = 0;
      this.timer = setInterval(() => {
        if (second2 > 0) {
          second2 = second2 - 1;
        } else {
          if (second1 > 0) {
            second1 = second1 - 1;
            second2 = 9;
          } else {
            if (min > 0) {
              min = min - 1;
              second1 = 5;
              second2 = 9;
            } else {
              this.disabledCount = false;
              clearInterval(this.timer);
            }
          }
        }
        this.countDown = `${min}分${second1}${second2}秒`;
      }, 1000);
    },
    // 初始化
    onInit() {
      this.getDishListTypeApi();
      this.dishSearchListApi();
    },
    // 导入成功
    exprotInit() {
      this.sendAgain(0);
      this.onInit();
    },
    // 重置搜索
    reset() {
      this.$refs["formValidate"].resetFields();
      this.pages.page = 1;
      this.onInit();
    },
    onBeforeUpload(file) {
      this.file = file;
    },
    // 导出
    onExport() { },
    // 添加
    onAdd() {
      this.$refs["addDishesModal"].show();
    },
    // 删除
    onDelete(row) {
      localDishDelete({
        dishCode: row.dishCode
      }).then(res => {
        if (res.retCode === 2000) {
          this.$Message.success("菜肴删除成功.");
          this.onInit();
        }
      });
    },
    // 导入错误
    onError(data) {
      console.log(data);
      if (data.retCode == 2888) {
        let content = "";
        if (data.data.result == -1) {
          data.data.list.map(it => {
            content += `<p style="margin-top:5px">${it}</p>`;
          });
          this.$Modal.warning({
            title: data.retMsg,
            content: content,
            width: "600",
            okText: "关闭"
          });
        }
        if (data.data.result == -2) {
          data.data.dishList.map(it => {
            content += `<p style="margin-top:5px">${it}</p>`;
          });
          this.$Modal.confirm({
            title: data.retMsg,
            content: content,
            width: "600",
            okText: "确认覆盖",
            cancelText: "跳过",
            onOk: () => {
              this.sendAgain(1);
            },
            onCancel: () => {
              this.sendAgain(0);
            }
          });
        }
      }
    },
    // 导入
    onImport() {
      this.$refs["cusUploadNutritionTagModal"].show();
    },
    // 营养标签
    onDetail(row) {
      this.$refs["dishesTags"].form.dishCode = row.dishCode;
      this.$refs["dishesTags"].form.dishName = row.dishName;
      this.$refs["dishesTags"].show();
    },
    // 编辑
    onEdit(row) {
      this.$refs["addDishesModal"].form.dishCode = row.dishCode;
      this.$refs["addDishesModal"].show();
    },

    // 是否状态切换 val为0切换有价格 为1切换可用
    ifSwitchChange(row, val) {
      if (val) {
        this.postApiUpdateDishUsableStatus(row.dishCode)
      } else {
        this.postApiBasicUdateDishStatusApi(row.dishCode);
      }

    },
    // 查询列表
    dishSearchListApi() {
      this.loading = true;
      return new Promise(resolve => {

        let obj = this.dishForm;
        obj.current = this.pages.page;
        obj.size = this.pages.pageSize;
        dishSearchList(obj).then(res => {
          this.loading = false;
          if (res.retCode === 2000) {
            res.data.forEach(element => {
              element.dishStatus = element.dishStatus === 1 ? true : false;
              element.usableStatus = element.usableStatus === 1 ? true : false;
            });
            this.data = res.data;
            this.pages.pageTotal = res.total;
            resolve();
          }
        });
      });
    },
    // 获取菜肴分类
    getDishListTypeApi() {
      return new Promise(resolve => {
        getDishListType({}).then(res => {
          if (res.retCode === 2000) {
            this.materialTypeList = res.data;
            resolve();
          }
        });
      });
    },
    // 覆盖或者跳过
    sendAgain(type) {
      this.$cu.showLoading();
      let params = new FormData();
      params.append("type", type);
      params.append("file", this.file);
      this.inportLocalDishExcel(params)
        .then(res => {
          if (res.code === 1 || res.retCode === 2000) {
            this.$cu.hideLoading();
            this.$Message.success("上传成功");
          }
        })
        .catch(() => this.$cu.hideLoading(1.5));
    },
    //本地菜肴模块-是否常用状态-------接口
    postApiBasicUdateDishStatusApi(v) {
      return new Promise(resolve => {
        let params = {
          dishCode: v
        };
        postApiBasicUdateDishStatus(params).then(res => {
          if (res.retCode == 2000) {
            this.dishSearchListApi();
            resolve(res);
          } else {
            // this.$Message.error(res.retMsg);
            this.$refs["dishStatusModal"].show = true;
            this.dishStatusErrorList = res.data;
            setTimeout(() => {
              this.dishSearchListApi();
            }, 30);
          }
        });
      });
    },
    // 本地菜肴模块 是否可用 --------接口

    postApiUpdateDishUsableStatus(v) {
      return new Promise(resolve => {
        let params = {
          dishCode: v
        };
        postApiUpdateDishUsableStatus(params).then(res => {
          if (res.retCode == 2000) {
            this.dishSearchListApi();
            resolve(res);
          } else {
            // this.$Message.error(res.retMsg);
            this.$refs["dishStatusModal"].show = true;
            this.dishStatusErrorList = res.data;
            setTimeout(() => {
              this.dishSearchListApi();
            }, 30);
          }
        });
      });
    }
  },
  destroyed() {
    clearInterval(this.timer);
    window.removeEventListener("resize", this.resizeHandle, true);
  }
};
</script>
<style lang="less" scoped>
::v-deep.ivu-input-icon {
  height: 40px !important;
  line-height: 40px !important;
}

/deep/.ivu-form-item {
  margin-bottom: 20px;
}

.content {

  // padding: 20px;
  &-bottom {
    background: #fff;
    border-radius: 6px;
    box-shadow: 1px 1px 2px 0px rgba(153, 182, 199, 0.2);
    padding: 20px;
  }
}

.formBox {
  width: 100%;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0px 4px 8px 0px rgba(108, 137, 165, 0.18);
  padding: 20px 20px 1px;
  display: flex;
  flex-wrap: wrap;

  &-item {
    margin-right: 48px;
  }
}

.mr_20 {
  margin-right: 20px;
}

.btnBox {
  width: 100%;
  display: flex;
  justify-content: space-between;

  // margin-bottom: 20px;
  div {
    display: flex;
  }
}
</style>
